<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>
    // reducer 函数接收4个参数:
    // Accumulator (acc) (累计器)
    // Current Value (cur) (当前值)
    // Current Index (idx) (当前索引)
    // Source Array (src) (源数组)

    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));


    function reduce(arr, reduceCallback, initialValue) {
      // 首先，检查传递的参数是否正确。
      if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function') {
        return [];
      } else {
        // 如果没有将initialValue传递给该函数，我们将使用第一个数组项作为initialValue
        let hasInitialValue = initialValue !== undefined;
        let value = hasInitialValue ? initialValue : arr[0];
        // 如果有传递 initialValue，则索引从 1 开始，否则从 0 开始
        for (let i = hasInitialValue ? 1 : 0, len = arr.length; i < len; i++) {
          value = reduceCallback(value, arr[i], i, arr); 
        }
        return value;
      }
    }
  </script>
</body>
</html>